<template>
  <div class="team-members-page">
    <!-- 初始加载状态 -->
    <PageLoading 
      v-if="initialLoading"
      :title="isRefreshing ? '正在刷新团队成员数据' : '正在加载团队成员数据'"
      :subtitle="isRefreshing ? '请稍候，正在更新数据...' : '请稍候，正在为您准备数据...'"
    />
    <div v-else v-loading="loading">
    <div class="page-header">
      <div class="header-left">
        <h1 class="page-title">项目成员管理</h1>
        <p class="page-subtitle">集中管理各项目团队成员，支持快速筛选、编辑与分配</p>
      </div>
      <div class="header-actions">
        <el-button :loading="tableLoading" @click="handleRefresh">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
        <el-button type="primary" @click="openAddDialog">
          <el-icon><Plus /></el-icon>
          添加成员
        </el-button>
      </div>
    </div>

    <el-row :gutter="16" class="stats-row">
      <el-col :xs="24" :sm="8">
        <div class="stat-card primary">
          <div class="stat-icon">
            <el-icon><UserFilled /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ statistics.total_members }}</div>
            <div class="stat-label">成员总数</div>
          </div>
        </div>
      </el-col>
      <el-col :xs="24" :sm="8">
        <div class="stat-card success">
          <div class="stat-icon">
            <el-icon><User /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ statistics.active_members }}</div>
            <div class="stat-label">活跃成员</div>
          </div>
        </div>
      </el-col>
      <el-col :xs="24" :sm="8">
        <div class="stat-card warning">
          <div class="stat-icon">
            <el-icon><Remove /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ statistics.inactive_members }}</div>
            <div class="stat-label">禁用成员</div>
          </div>
        </div>
      </el-col>
    </el-row>

    <el-card class="filter-card" shadow="never">
      <el-form :inline="true" :model="filters" class="filter-form">
        <el-form-item label="所属项目">
          <el-select
            v-model="filters.project_id"
            placeholder="请选择项目"
            filterable
            clearable
            style="min-width: 200px"
            @change="handleFilterChange"
            @clear="handleProjectClear"
          >
            <el-option
              v-for="option in projectFilterOptions"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="成员角色">
          <el-select
            v-model="filters.role"
            placeholder="全部角色"
            clearable
            style="min-width: 160px"
            @change="handleFilterChange"
          >
            <el-option v-for="option in roleOptions" :key="option.value" :label="option.label" :value="option.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="用户状态">
          <el-select
            v-model="filters.status"
            placeholder="全部状态"
            clearable
            style="min-width: 140px"
            @change="handleFilterChange"
          >
            <el-option label="活跃" value="active" />
            <el-option label="禁用" value="inactive" />
            <el-option label="已删除" value="deleted" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-input
            v-model="filters.keyword"
            placeholder="搜索成员、邮箱或项目"
            clearable
            prefix-icon="Search"
            style="width: 240px"
            @clear="handleFilterChange"
            @keyup.enter="handleFilterChange"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleFilterChange">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleResetFilters">
            <el-icon><RefreshRight /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-row :gutter="16" class="content-row">
      <el-col :xs="24" :md="17">
        <el-card class="table-card" shadow="never">
          <template #header>
            <div class="card-header">
              <span>成员列表</span>
              <span class="card-sub">共 {{ pagination.total }} 条记录</span>
            </div>
          </template>
          <el-table 
            :data="members" 
            :style="{ width: '100%' }" 
            v-loading="tableLoading"
            :row-class-name="getRowClassName"
            class="member-table"
          >
            <el-table-column label="成员" min-width="240">
              <template #default="{ row }">
                <div class="member-info">
                  <el-avatar 
                    :size="44" 
                    :src="getAvatarUrl(row.member.avatar)"
                    class="member-avatar"
                  >
                    {{ (row.member.name || row.member.username || row.member.email || '?').charAt(0).toUpperCase() }}
                  </el-avatar>
                  <div class="member-meta">
                    <div class="member-name-row">
                      <span class="member-name">{{ row.member.name || row.member.username || '未命名用户' }}</span>
                      <el-tag 
                        v-if="row.member.status" 
                        :type="getStatusTagType(row.member.status)" 
                        size="small" 
                        effect="plain"
                        class="member-status-tag"
                      >
                        {{ getStatusLabel(row.member.status) }}
                      </el-tag>
                    </div>
                    <div class="member-details">
                      <span v-if="row.member.username" class="member-username">@{{ row.member.username }}</span>
                      <el-divider v-if="row.member.username && row.member.email" direction="vertical" />
                      <span class="member-email">{{ row.member.email || '未设置邮箱' }}</span>
                    </div>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="所属项目" min-width="200">
              <template #default="{ row }">
                <div class="project-info">
                  <span class="project-name">{{ row.project.name }}</span>
                  <el-tag v-if="row.project.is_archived" size="small" type="info" class="ml-4">已归档</el-tag>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="角色" width="120" align="center">
              <template #default="{ row }">
                <el-tag v-if="row.role_names && row.role_names.length > 0" :type="getRoleTagType(row.role_codes?.[0] || row.role)">
                  {{ row.role_names[0] }}
                </el-tag>
                <el-tag v-else :type="getRoleTagType(row.role)">{{ getRoleLabel(row.role) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="项目权限" min-width="220">
              <template #default="{ row }">
                <div class="permission-tags" v-if="row.permissions.length">
                  <el-tag
                    v-for="perm in row.permissions"
                    :key="perm"
                    size="small"
                    class="permission-tag"
                  >
                    {{ getPermissionLabel(perm) }}
                  </el-tag>
                </div>
                <span v-else class="empty-hint">默认权限</span>
              </template>
            </el-table-column>
            <el-table-column label="加入时间" width="180">
              <template #default="{ row }">
                {{ formatDateTime(row.joined_at) }}
              </template>
            </el-table-column>
            <el-table-column label="状态" width="120" align="center">
              <template #default="{ row }">
                <el-tag :type="getStatusTagType(row.member.status)">{{ getStatusLabel(row.member.status) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="160" fixed="right">
              <template #default="{ row }">
                <el-button type="primary" link size="small" @click="openEditDialog(row)">
                  编辑
                </el-button>
                <el-button type="danger" link size="small" @click="handleRemove(row)" :disabled="actionLoading">
                  移除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <div class="table-footer">
            <el-pagination
              background
              layout="total, sizes, prev, pager, next"
              :current-page="pagination.page"
              :page-size="pagination.size"
              :page-sizes="[10, 20, 30, 50]"
              :total="pagination.total"
              @current-change="handlePageChange"
              @size-change="handleSizeChange"
            />
          </div>
        </el-card>
      </el-col>

      <el-col :xs="24" :md="7">
        <el-card class="side-card" shadow="never">
          <template #header>
            <div class="card-header">
              <span>角色分布</span>
            </div>
          </template>
          <el-empty v-if="!roleDistribution.length" description="暂无数据" />
          <div v-else class="distribution-list">
            <div v-for="item in roleDistribution" :key="item.role" class="distribution-item">
              <div class="distribution-label">
                <el-tag :type="getRoleTagType(item.role)" size="small">{{ getRoleLabel(item.role) }}</el-tag>
              </div>
              <div class="distribution-bar">
                <div class="distribution-progress" :style="{ width: `${item.percent}%` }"></div>
              </div>
              <div class="distribution-value">{{ item.count }}</div>
            </div>
          </div>
        </el-card>

        <el-card class="side-card" shadow="never" style="margin-top: 16px;">
          <template #header>
            <div class="card-header">
              <span>项目成员Top</span>
            </div>
          </template>
          <el-empty v-if="!projectDistribution.length" description="暂无数据" />
          <div v-else class="project-distribution">
            <div v-for="item in projectDistribution" :key="item.project_id" class="project-item">
              <div class="project-name" :title="item.project_name">{{ item.project_name || '未命名项目' }}</div>
              <div class="project-count">{{ item.count }} 人</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 添加成员 -->
    <el-dialog
      v-model="addDialogVisible"
      title="添加团队成员"
      width="520px"
      :close-on-click-modal="false"
    >
      <el-form ref="addFormRef" :model="addForm" :rules="addFormRules" label-width="90px">
        <el-form-item label="所属项目" prop="project_id">
          <el-select v-model="addForm.project_id" placeholder="选择项目" filterable clearable>
            <el-option v-for="option in projectOptions" :key="option.value" :label="option.label" :value="option.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="选择用户" prop="user_id">
          <el-select
            v-model="addForm.user_id"
            placeholder="搜索用户"
            filterable
            remote
            :remote-method="remoteSearchUsers"
            :loading="userSearchLoading"
            clearable
          >
            <el-option
              v-for="user in userOptions"
              :key="user.id"
              :label="`${user.name || user.username || '未命名用户'} (${user.email || '无邮箱'})`"
              :value="user.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="成员角色" prop="role">
          <el-select v-model="addForm.role" placeholder="选择角色">
            <el-option v-for="option in roleOptions" :key="option.value" :label="option.label" :value="option.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="项目权限">
          <div class="permissions-section">
            <div class="permissions-header">
              <span class="permissions-title">选择权限</span>
              <el-button 
                text 
                size="small" 
                @click="selectAllAddPermissions"
                class="select-all-btn"
              >
                全选
              </el-button>
              <el-button 
                text 
                size="small" 
                @click="clearAllAddPermissions"
                class="clear-all-btn"
              >
                清空
              </el-button>
            </div>
            <el-checkbox-group v-model="addForm.permissions" class="permissions-group">
              <el-collapse v-model="activePermissionModules" class="permission-modules">
                <el-collapse-item 
                  v-for="(moduleInfo, moduleKey) in PERMISSION_MODULES" 
                  :key="moduleKey"
                  :name="moduleKey"
                  class="permission-module-item"
                >
                  <template #title>
                    <div class="module-header">
                      <span class="module-title">{{ moduleInfo.label }}</span>
                      <el-button 
                        text 
                        size="small" 
                        @click.stop="selectModuleAddPermissions(moduleKey)"
                        class="module-select-btn"
                      >
                        全选
                      </el-button>
                      <el-button 
                        text 
                        size="small" 
                        @click.stop="clearModuleAddPermissions(moduleKey)"
                        class="module-clear-btn"
                      >
                        清空
                      </el-button>
                    </div>
                  </template>
                  <div class="module-permissions">
                    <div 
                      v-for="perm in permissionOptionsByModule[moduleKey] || []" 
                      :key="perm.value" 
                      class="permission-item"
                    >
                      <el-checkbox :label="perm.value" class="permission-checkbox">
                        <div class="permission-content">
                          <span class="permission-label">{{ perm.label }}</span>
                          <span class="permission-code">{{ perm.value }}</span>
                        </div>
                      </el-checkbox>
                    </div>
                  </div>
                </el-collapse-item>
              </el-collapse>
            </el-checkbox-group>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="actionLoading" @click="handleAddMember">确定</el-button>
      </template>
    </el-dialog>

    <!-- 编辑成员 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑项目成员"
      width="600px"
      :close-on-click-modal="false"
      class="edit-member-dialog"
    >
      <div class="dialog-content">
        <!-- 成员信息卡片 -->
        <div class="member-info-card">
          <el-avatar :size="48" :src="getAvatarUrl(editForm.avatar)" class="member-avatar-large">
            {{ (editForm.name || editForm.username || '?').charAt(0).toUpperCase() }}
          </el-avatar>
          <div class="member-info-details">
            <div class="member-name-large">{{ editForm.name || editForm.username || '未命名用户' }}</div>
            <div class="member-email-large">{{ editForm.email || '未设置邮箱' }}</div>
            <div class="member-project-badge">
              <el-icon><FolderOpened /></el-icon>
              <span>{{ editForm.project_name || '未关联项目' }}</span>
            </div>
          </div>
        </div>

        <el-divider />

        <el-form ref="editFormRef" :model="editForm" :rules="editFormRules" label-width="100px" class="edit-form">
          <el-form-item label="成员角色" prop="roles">
            <el-select 
              v-model="editForm.roles" 
              placeholder="选择角色（可多选）" 
              multiple
              filterable
              style="width: 100%"
              :loading="projectRolesLoading"
            >
              <el-option
                v-for="role in projectRoles"
                :key="role.id"
                :label="role.name"
                :value="role.id"
              >
                <div class="role-option">
                  <span class="role-name">{{ role.name }}</span>
                  <span v-if="role.description" class="role-description">{{ role.description }}</span>
                  <el-tag v-if="role.is_system" size="small" type="info" class="role-system-tag">系统</el-tag>
                </div>
              </el-option>
            </el-select>
            <div class="form-hint">
              <el-icon><InfoFilled /></el-icon>
              <span>可以为成员分配多个项目角色，角色将决定成员的基础权限</span>
            </div>
          </el-form-item>

          <el-form-item label="项目权限">
            <div class="permissions-section">
              <div class="permissions-header">
                <span class="permissions-title">选择项目权限</span>
                <el-button 
                  text 
                  size="small" 
                  @click="selectAllPermissions"
                  class="select-all-btn"
                >
                  全选
                </el-button>
                <el-button 
                  text 
                  size="small" 
                  @click="clearAllPermissions"
                  class="clear-all-btn"
                >
                  清空
                </el-button>
              </div>
              <el-checkbox-group v-model="editForm.permissions" class="permissions-group">
                <el-collapse v-model="activePermissionModules" class="permission-modules">
                  <el-collapse-item 
                    v-for="(moduleInfo, moduleKey) in PERMISSION_MODULES" 
                    :key="moduleKey"
                    :name="moduleKey"
                    class="permission-module-item"
                  >
                    <template #title>
                      <div class="module-header">
                        <span class="module-title">{{ moduleInfo.label }}</span>
                        <el-button 
                          text 
                          size="small" 
                          @click.stop="selectModulePermissions(moduleKey)"
                          class="module-select-btn"
                        >
                          全选
                        </el-button>
                        <el-button 
                          text 
                          size="small" 
                          @click.stop="clearModulePermissions(moduleKey)"
                          class="module-clear-btn"
                        >
                          清空
                        </el-button>
                      </div>
                    </template>
                    <div class="module-permissions">
                      <div 
                        v-for="perm in permissionOptionsByModule[moduleKey] || []" 
                        :key="perm.value" 
                        class="permission-item"
                      >
                        <el-checkbox :label="perm.value" class="permission-checkbox">
                          <div class="permission-content">
                            <span class="permission-label">{{ perm.label }}</span>
                            <span class="permission-code">{{ perm.value }}</span>
                          </div>
                        </el-checkbox>
                      </div>
                    </div>
                  </el-collapse-item>
                </el-collapse>
              </el-checkbox-group>
              <div v-if="editForm.permissions.length === 0" class="permissions-empty">
                <el-icon><Warning /></el-icon>
                <span>未选择任何权限，成员将使用默认权限</span>
              </div>
            </div>
          </el-form-item>
        </el-form>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editDialogVisible = false" size="default">取消</el-button>
          <el-button 
            type="primary" 
            :loading="actionLoading" 
            @click="handleUpdateMember"
            size="default"
          >
            <el-icon v-if="!actionLoading"><Check /></el-icon>
            保存更改
          </el-button>
        </div>
      </template>
    </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { Plus, Refresh, RefreshRight, Remove, Search, User, UserFilled } from '@element-plus/icons-vue'

import { getProjectList } from '@/api/project'
import { getUserList } from '@/api/users'
import { getRoles, type Role } from '@/api/roles'
import PageLoading from '@/components/ui/PageLoading.vue'
import { getAvatarUrl } from '@/utils/avatar'
import {
  addTeamMember,
  getTeamMembers,
  removeTeamMember,
  updateTeamMember
} from '@/api/team-members'
import type {
  TeamMemberListResponse,
  TeamMemberQueryParams,
  TeamMemberRecord
} from '@/types/team-member'
import { PROJECT_PERMISSIONS, PERMISSION_MODULES, type ProjectMemberRole } from '@/types/project'
import { FolderOpened, InfoFilled, Warning, Check } from '@element-plus/icons-vue'

interface ProjectOption {
  label: string
  value: string
}

interface UserOption {
  id: string
  name?: string
  username?: string
  email?: string
  avatar?: string
}

const loading = ref(false)
const tableLoading = ref(false)
const actionLoading = ref(false)
const initialLoading = ref(true)
const isRefreshing = ref(false)

const members = ref<TeamMemberRecord[]>([])
const statistics = reactive({
  total_members: 0,
  active_members: 0,
  inactive_members: 0,
  by_role: {} as Record<string, number>,
  by_project: [] as Array<{ project_id: string; project_name?: string; count: number }>
})

const pagination = reactive({
  page: 1,
  size: 20,
  total: 0
})

const filters = reactive({
  project_id: '' as string | undefined,
  role: '' as ProjectMemberRole | '' | undefined,
  status: '' as string | undefined,
  keyword: ''
})

const projectOptions = ref<ProjectOption[]>([])
const projectFilterOptions = computed<ProjectOption[]>(() => projectOptions.value)
const roleOptions = [
  { label: '项目负责人', value: 'owner' },
  { label: '管理员', value: 'manager' },
  { label: '开发人员', value: 'developer' },
  { label: '测试人员', value: 'tester' },
  { label: '设计师', value: 'designer' },
  { label: '分析师', value: 'analyst' },
  { label: '查看者', value: 'viewer' }
] satisfies Array<{ label: string; value: ProjectMemberRole }>

// 按模块分组的权限选项
const permissionOptionsByModule = computed(() => {
  const grouped: Record<string, Array<{ label: string; value: string }>> = {}
  PROJECT_PERMISSIONS.forEach(perm => {
    const module = perm.module || 'other'
    if (!grouped[module]) {
      grouped[module] = []
    }
    grouped[module].push({
      label: perm.label,
      value: perm.value
    })
  })
  return grouped
})

// 所有权限选项（用于向后兼容）
const permissionOptions = computed(() => {
  return PROJECT_PERMISSIONS.map(option => ({
    label: option.label,
    value: option.value
  }))
})

// 权限模块折叠状态
const activePermissionModules = ref<string[]>(['project', 'requirement', 'task', 'defect', 'test_case'])

const permissionAliasMap: Record<string, string> = {
  'project:write': 'project:update',
  'project:view': 'project:read',
  'project:manage-member': 'project:manage_members'
}

const legacyPermissionAlias: Record<string, string> = {
  'project:write': '编辑项目',
  'project:view': '查看项目',
  'project:manage-member': '管理成员'
}

const userOptions = ref<UserOption[]>([])
const userSearchLoading = ref(false)

const addDialogVisible = ref(false)
const editDialogVisible = ref(false)

const addFormRef = ref<FormInstance>()
const editFormRef = ref<FormInstance>()

const addForm = reactive({
  project_id: '' as string | undefined,
  user_id: '' as string | undefined,
  role: 'developer' as ProjectMemberRole,
  permissions: ['project:read'] as string[]
})

const editForm = reactive({
  project_id: '',
  project_name: '',
  user_id: '',
  username: '',
  name: '',
  email: '',
  avatar: '',
  role: 'developer' as ProjectMemberRole, // 向后兼容
  roles: [] as string[], // 多角色支持
  permissions: [] as string[]
})

const addFormRules: FormRules<typeof addForm> = {
  project_id: [{ required: true, message: '请选择项目', trigger: 'change' }],
  user_id: [{ required: true, message: '请选择用户', trigger: 'change' }],
  role: [{ required: true, message: '请选择角色', trigger: 'change' }]
}

const editFormRules: FormRules<typeof editForm> = {
  roles: [{ required: true, message: '请至少选择一个角色', trigger: 'change', type: 'array', min: 1 }]
}

// 项目角色列表
const projectRoles = ref<Role[]>([])
const projectRolesLoading = ref(false)

// 加载项目角色列表
const loadProjectRoles = async () => {
  if (projectRoles.value.length > 0) return // 已加载
  
  projectRolesLoading.value = true
  try {
    const roles = await getRoles('project')
    projectRoles.value = roles.filter(role => role.is_active)
  } catch (error) {
    console.error('获取项目角色列表失败:', error)
    ElMessage.warning('获取项目角色列表失败，使用默认角色')
    // 使用默认角色选项作为后备
    projectRoles.value = roleOptions.map(opt => ({
      id: opt.value,
      name: opt.label,
      code: opt.value,
      description: '',
      permissions: [],
      is_system: true,
      is_active: true,
      scope: 'project' as const
    }))
  } finally {
    projectRolesLoading.value = false
  }
}

const roleDistribution = computed(() => {
  const total = Object.values(statistics.by_role).reduce((acc, cur) => acc + cur, 0) || 1
  return Object.entries(statistics.by_role).map(([role, count]) => ({
    role: role as ProjectMemberRole,
    count,
    percent: Math.min(100, Math.round((count / total) * 100))
  }))
})

const projectDistribution = computed(() => statistics.by_project.slice(0, 6))

const fetchProjects = async () => {
  try {
    const res = await getProjectList({ page: 1, size: 100 })
    projectOptions.value = res.items.map(project => ({
      label: project.name,
      value: project.id
    }))
    
    // 如果项目列表不为空且当前没有选择项目，默认选择第一个项目
    if (projectOptions.value.length > 0 && !filters.project_id) {
      filters.project_id = projectOptions.value[0].value
    }
  } catch (error) {
    console.error('获取项目列表失败', error)
  }
}

const fetchMembers = async () => {
  tableLoading.value = true
  try {
    // 如果没有选择项目，但有项目列表，默认选择第一个项目
    let projectId = filters.project_id
    if (!projectId && projectOptions.value.length > 0) {
      projectId = projectOptions.value[0].value
      filters.project_id = projectId
    }
    
    // 如果没有项目列表，无法加载成员数据
    if (!projectId) {
      members.value = []
      pagination.total = 0
      tableLoading.value = false
      return
    }
    
    const params: TeamMemberQueryParams = {
      project_id: projectId,
      role: filters.role || undefined,
      status: filters.status || undefined,
      keyword: filters.keyword || undefined,
      page: pagination.page,
      size: pagination.size,
      sort_by: 'joined_at',
      sort_order: -1
    }

    const response: TeamMemberListResponse = await getTeamMembers(params)
    members.value = response.items.map(item => ({
      ...item,
      permissions: Array.from(
        new Set(
          item.permissions.map(permission => permissionAliasMap[permission] || permission)
        )
      )
    }))
    pagination.total = response.pagination.total ?? members.value.length
    pagination.page = response.pagination.page
    pagination.size = response.pagination.size

    statistics.total_members = response.statistics.total_members
    statistics.active_members = response.statistics.active_members
    statistics.inactive_members = response.statistics.inactive_members
    statistics.by_role = response.statistics.by_role || {}
    statistics.by_project = response.statistics.by_project || []
  } catch (error) {
    console.error('获取团队成员失败', error)
    ElMessage.error('获取团队成员失败，请稍后重试')
  } finally {
    tableLoading.value = false
  }
}

const handleFilterChange = () => {
  pagination.page = 1
  fetchMembers()
}

const handleProjectClear = () => {
  // 当清空项目选择时，自动选择第一个项目
  if (projectOptions.value.length > 0) {
    filters.project_id = projectOptions.value[0].value
    handleFilterChange()
  }
}

const handleResetFilters = () => {
  // 重置时，如果有项目列表，默认选择第一个项目
  if (projectOptions.value.length > 0) {
    filters.project_id = projectOptions.value[0].value
  } else {
    filters.project_id = ''
  }
  filters.role = ''
  filters.status = ''
  filters.keyword = ''
  pagination.page = 1
  fetchMembers()
}

const handlePageChange = (page: number) => {
  pagination.page = page
  fetchMembers()
}

const handleSizeChange = (size: number) => {
  pagination.size = size
  pagination.page = 1
  fetchMembers()
}

const handleRefresh = async () => {
  try {
    isRefreshing.value = true
    initialLoading.value = true
    await fetchMembers()
    ElMessage.success('刷新成功')
  } catch (error) {
    console.error('刷新失败:', error)
    ElMessage.error('刷新失败，请稍后重试')
  } finally {
    setTimeout(() => {
      initialLoading.value = false
      isRefreshing.value = false
    }, 300)
  }
}

const openAddDialog = () => {
  addForm.project_id = filters.project_id || undefined
  addForm.user_id = undefined
  addForm.role = 'developer'
  addForm.permissions = ['project:read']
  addDialogVisible.value = true
  if (!projectOptions.value.length) {
    fetchProjects()
  }
  remoteSearchUsers('')
}

const openEditDialog = async (record: TeamMemberRecord) => {
  editForm.project_id = record.project.id
  editForm.project_name = record.project.name
  editForm.user_id = record.member.id
  editForm.username = record.member.username || ''
  editForm.name = record.member.name || ''
  editForm.email = record.member.email || ''
  editForm.avatar = record.member.avatar || ''
  
  // 支持多角色：优先使用 roles 数组，如果没有则使用单个 role
  if (record.roles && record.roles.length > 0) {
    editForm.roles = record.roles
    // 向后兼容：设置单个 role
    editForm.role = (record.role_codes?.[0] || record.role) as ProjectMemberRole
  } else if (record.role) {
    // 如果没有 roles 数组，尝试从 role 代码查找对应的角色ID
    editForm.role = record.role
    editForm.roles = []
    // 如果项目角色列表已加载，尝试匹配
    if (projectRoles.value.length > 0) {
      const matchedRole = projectRoles.value.find(r => r.code === record.role)
      if (matchedRole) {
        editForm.roles = [matchedRole.id]
      }
    }
  } else {
    editForm.role = 'developer'
    editForm.roles = []
  }
  
  editForm.permissions = [
    ...new Set(record.permissions.map(permission => permissionAliasMap[permission] || permission))
  ]
  
  editDialogVisible.value = true
  
  // 加载项目角色列表
  await loadProjectRoles()
  
  // 如果 roles 为空但 role 有值，尝试匹配
  if (editForm.roles.length === 0 && editForm.role) {
    const matchedRole = projectRoles.value.find(r => r.code === editForm.role)
    if (matchedRole) {
      editForm.roles = [matchedRole.id]
    }
  }
}

const remoteSearchUsers = async (query: string) => {
  userSearchLoading.value = true
  try {
    const res = await getUserList({
      page: 1,
      size: 20,
      username: query,
      email: query,
      status: 'active'
    })

    const data = res.data?.data ?? []
    const items = Array.isArray(data)
      ? data
      : Array.isArray(data?.items)
        ? data.items
        : []

    userOptions.value = items.map((item: any) => ({
      id: item.id,
      name: item.name,
      username: item.username,
      email: item.email,
      avatar: item.avatar
    }))
  } catch (error) {
    console.error('搜索用户失败', error)
  } finally {
    userSearchLoading.value = false
  }
}

const handleAddMember = async () => {
  if (!addFormRef.value) return
  const valid = await addFormRef.value.validate()
  if (!valid || !addForm.project_id || !addForm.user_id) return

  actionLoading.value = true
  try {
    await addTeamMember({
      project_id: addForm.project_id,
      user_id: addForm.user_id,
      role: addForm.role,
        permissions: addForm.permissions.map(permission => permissionAliasMap[permission] || permission)
    })
    ElMessage.success('成员添加成功')
    addDialogVisible.value = false
    await fetchMembers()
  } catch (error) {
    console.error('添加成员失败', error)
    ElMessage.error('添加成员失败，请稍后重试')
  } finally {
    actionLoading.value = false
  }
}

const handleUpdateMember = async () => {
  if (!editFormRef.value) return
  const valid = await editFormRef.value.validate()
  if (!valid) return

  // 验证至少选择了一个角色
  if (!editForm.roles || editForm.roles.length === 0) {
    ElMessage.warning('请至少选择一个角色')
    return
  }

  actionLoading.value = true
  try {
    // 优先使用 roles 数组，如果没有则使用 role 代码
    const updatePayload: any = {
      permissions: editForm.permissions.map(
        permission => permissionAliasMap[permission] || permission
      )
    }
    
    // 如果 roles 数组有值，使用 roles；否则使用 role 代码（向后兼容）
    if (editForm.roles && editForm.roles.length > 0) {
      updatePayload.roles = editForm.roles
    } else if (editForm.role) {
      updatePayload.role = editForm.role
    }
    
    await updateTeamMember(editForm.project_id, editForm.user_id, updatePayload)
    ElMessage.success('成员更新成功')
    editDialogVisible.value = false
    await fetchMembers()
  } catch (error) {
    console.error('更新成员失败', error)
    ElMessage.error('更新成员失败，请稍后重试')
  } finally {
    actionLoading.value = false
  }
}

// 全选权限（编辑）
const selectAllPermissions = () => {
  editForm.permissions = permissionOptions.value.map(perm => perm.value)
}

// 清空权限（编辑）
const clearAllPermissions = () => {
  editForm.permissions = []
}

// 选择模块权限（编辑）
const selectModulePermissions = (moduleKey: string) => {
  const modulePerms = permissionOptionsByModule.value[moduleKey] || []
  const modulePermValues = modulePerms.map(perm => perm.value)
  // 合并到现有权限，去重
  const newPermissions = Array.from(new Set([...editForm.permissions, ...modulePermValues]))
  editForm.permissions = newPermissions
}

// 清空模块权限（编辑）
const clearModulePermissions = (moduleKey: string) => {
  const modulePerms = permissionOptionsByModule.value[moduleKey] || []
  const modulePermValues = modulePerms.map(perm => perm.value)
  // 从现有权限中移除该模块的权限
  editForm.permissions = editForm.permissions.filter(perm => !modulePermValues.includes(perm))
}

// 全选权限（添加）
const selectAllAddPermissions = () => {
  addForm.permissions = permissionOptions.value.map(perm => perm.value)
}

// 清空权限（添加）
const clearAllAddPermissions = () => {
  addForm.permissions = []
}

// 选择模块权限（添加）
const selectModuleAddPermissions = (moduleKey: string) => {
  const modulePerms = permissionOptionsByModule.value[moduleKey] || []
  const modulePermValues = modulePerms.map(perm => perm.value)
  // 合并到现有权限，去重
  const newPermissions = Array.from(new Set([...addForm.permissions, ...modulePermValues]))
  addForm.permissions = newPermissions
}

// 清空模块权限（添加）
const clearModuleAddPermissions = (moduleKey: string) => {
  const modulePerms = permissionOptionsByModule.value[moduleKey] || []
  const modulePermValues = modulePerms.map(perm => perm.value)
  // 从现有权限中移除该模块的权限
  addForm.permissions = addForm.permissions.filter(perm => !modulePermValues.includes(perm))
}

const handleRemove = (record: TeamMemberRecord) => {
  ElMessageBox.confirm(
    `确定从项目「${record.project.name}」中移除成员「${record.member.name || record.member.username || record.member.email}」吗？`,
    '提示',
    {
      type: 'warning',
      confirmButtonText: '确定',
      cancelButtonText: '取消'
    }
  )
    .then(async () => {
      actionLoading.value = true
      try {
        await removeTeamMember(record.project.id, record.member.id)
        ElMessage.success('成员已移除')
        await fetchMembers()
      } catch (error) {
        console.error('移除成员失败', error)
        ElMessage.error('移除成员失败，请稍后重试')
      } finally {
        actionLoading.value = false
      }
    })
    .catch(() => {})
}

const getRoleLabel = (role: string | ProjectMemberRole | null | undefined) => {
  const map: Record<string, string> = {
    owner: '项目负责人',
    manager: '管理员',
    developer: '开发人员',
    tester: '测试人员',
    designer: '设计师',
    analyst: '分析师',
    viewer: '查看者'
  }
  return map[role || ''] || '未知角色'
}

const getRoleTagType = (role: string | ProjectMemberRole | null | undefined) => {
  const map: Record<string, 'primary' | 'success' | 'warning' | 'info' | 'danger'> = {
    owner: 'danger',
    manager: 'warning',
    developer: 'primary',
    tester: 'success',
    designer: 'info',
    analyst: 'info',
    viewer: 'info'
  }
  return map[role || ''] || 'info'
}

const getStatusLabel = (status?: string | null) => {
  const map: Record<string, string> = {
    active: '活跃',
    inactive: '禁用',
    deleted: '已删除'
  }
  return map[status || ''] || '未知'
}

// 表格行类名
const getRowClassName = () => {
  return 'member-table-row'
}

const getStatusTagType = (status?: string | null) => {
  const map: Record<string, 'primary' | 'success' | 'warning' | 'info' | 'danger'> = {
    active: 'success',
    inactive: 'warning',
    deleted: 'info'
  }
  return map[status || ''] || 'info'
}

const getPermissionLabel = (permission: string) => {
  const canonical = permissionAliasMap[permission] || permission
  const found = permissionOptions.value.find(option => option.value === canonical)
  if (found) return found.label
  if (legacyPermissionAlias[permission]) return legacyPermissionAlias[permission]
  return canonical
}

const formatDateTime = (value?: string | null) => {
  if (!value) return '-'
  const date = new Date(value)
  if (Number.isNaN(date.getTime())) return value
  return date.toLocaleString('zh-CN')
}

onMounted(async () => {
  loading.value = true
  // 先加载项目列表，设置默认项目，然后再加载成员数据
  await fetchProjects()
  await fetchMembers()
  loading.value = false
  initialLoading.value = false
})
</script>

<style scoped>
.team-members-page {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: #fff;
  border-radius: 12px;
  padding: 20px 24px;
  box-shadow: 0 4px 12px rgba(31, 45, 61, 0.08);
}

.page-title {
  margin: 0;
  font-size: 22px;
  font-weight: 600;
  color: #1f2d3d;
}

.page-subtitle {
  margin: 4px 0 0;
  color: #86909c;
  font-size: 14px;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.stats-row {
  margin: 0;
}

.stat-card {
  display: flex;
  align-items: center;
  background: linear-gradient(135deg, #f5f7fa, #fff);
  border-radius: 12px;
  padding: 16px;
  box-shadow: 0 2px 10px rgba(31, 45, 61, 0.05);
  transition: transform 0.2s ease, box-shadow 0.2s ease;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 18px rgba(31, 45, 61, 0.08);
}

.stat-card.primary {
  background: linear-gradient(135deg, #409eff, #66b1ff);
  color: #fff;
}

.stat-card.success {
  background: linear-gradient(135deg, #67c23a, #95d475);
  color: #fff;
}

.stat-card.warning {
  background: linear-gradient(135deg, #e6a23c, #f3d19e);
  color: #fff;
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 12px;
  background: rgba(255, 255, 255, 0.28);
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
  font-size: 22px;
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 26px;
  font-weight: 600;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  opacity: 0.9;
}

.filter-card {
  border-radius: 12px;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

.content-row {
  margin-bottom: 24px;
}

.table-card {
  border-radius: 12px;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-weight: 600;
  color: #1f2d3d;
}

.card-sub {
  font-size: 13px;
  color: #8b9bb4;
}

.member-info {
  display: flex;
  align-items: center;
  gap: 14px;
  padding: 4px 0;
}

.member-avatar {
  flex-shrink: 0;
  border: 2px solid #f0f2f5;
  transition: all 0.3s ease;
}

.member-info:hover .member-avatar {
  border-color: #409eff;
  transform: scale(1.05);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.2);
}

.member-meta {
  display: flex;
  flex-direction: column;
  gap: 6px;
  flex: 1;
  min-width: 0;
}

.member-name-row {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

.member-name {
  font-weight: 600;
  font-size: 15px;
  color: #1f2937;
  line-height: 1.4;
  word-break: break-word;
}

.member-status-tag {
  font-size: 11px;
  height: 20px;
  line-height: 18px;
  padding: 0 6px;
  border-radius: 4px;
}

.member-details {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
  font-size: 13px;
}

.member-username {
  color: #6b7280;
  font-weight: 500;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
}

.member-email {
  color: #9ca3af;
  font-size: 13px;
  word-break: break-all;
  line-height: 1.4;
}

:deep(.el-divider--vertical) {
  margin: 0;
  height: 12px;
  border-color: #e5e7eb;
}

/* 表格样式优化 */
.member-table {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.member-table .el-table__row) {
  transition: all 0.3s ease;
}

:deep(.member-table .el-table__row:hover) {
  background-color: #f8fafc;
  transform: translateX(2px);
}

:deep(.member-table .el-table__row:hover .member-info) {
  transform: translateX(0);
}

:deep(.member-table .el-table__cell) {
  padding: 16px 12px;
  border-bottom: 1px solid #f0f2f5;
}

:deep(.member-table .el-table__header .el-table__cell) {
  background-color: #fafbfc;
  font-weight: 600;
  color: #374151;
  font-size: 14px;
  padding: 14px 12px;
}

.project-info {
  display: flex;
  align-items: center;
}

.project-name {
  color: #1f2d3d;
  font-weight: 500;
}

.permission-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.permission-tag {
  margin-right: 0;
}

.empty-hint {
  color: #8b9bb4;
  font-size: 13px;
}

.table-footer {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}

.side-card {
  border-radius: 12px;
  margin-bottom: 16px;
}

.distribution-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.distribution-item {
  display: grid;
  grid-template-columns: 120px 1fr 48px;
  align-items: center;
  gap: 12px;
}

.distribution-bar {
  height: 8px;
  background: #f2f6fc;
  border-radius: 4px;
  overflow: hidden;
}

.distribution-progress {
  height: 100%;
  background: linear-gradient(135deg, #409eff, #66b1ff);
}

.distribution-value {
  text-align: right;
  font-weight: 600;
  color: #1f2d3d;
}

.project-distribution {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.project-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 14px;
  color: #1f2d3d;
}

.project-name {
  flex: 1;
  margin-right: 12px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 编辑对话框样式 */
:deep(.edit-member-dialog) {
  .el-dialog__header {
    padding: 24px 24px 16px;
    border-bottom: 1px solid #f0f2f5;
    
    .el-dialog__title {
      font-size: 18px;
      font-weight: 600;
      color: #1f2d3d;
    }
  }
  
  .el-dialog__body {
    padding: 0;
  }
  
  .el-dialog__footer {
    padding: 16px 24px 24px;
    border-top: 1px solid #f0f2f5;
    background: #fafbfc;
  }
}

.dialog-content {
  padding: 24px;
}

.member-info-card {
  display: flex;
  align-items: flex-start;
  gap: 16px;
  padding: 20px;
  background: linear-gradient(135deg, #f8fafc 0%, #ffffff 100%);
  border-radius: 12px;
  border: 1px solid #e5e7eb;
}

.member-avatar-large {
  flex-shrink: 0;
  border: 3px solid #ffffff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.member-info-details {
  flex: 1;
  min-width: 0;
}

.member-name-large {
  font-size: 18px;
  font-weight: 600;
  color: #1f2d3d;
  margin-bottom: 6px;
  line-height: 1.4;
}

.member-email-large {
  font-size: 14px;
  color: #6b7280;
  margin-bottom: 12px;
  word-break: break-all;
}

.member-project-badge {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  padding: 6px 12px;
  background: #ecf5ff;
  border-radius: 6px;
  color: #409eff;
  font-size: 13px;
  font-weight: 500;
  
  .el-icon {
    font-size: 14px;
  }
}

.edit-form {
  margin-top: 8px;
  
  :deep(.el-form-item__label) {
    font-weight: 500;
    color: #374151;
  }
  
  :deep(.el-form-item) {
    margin-bottom: 24px;
  }
}

.form-hint {
  display: flex;
  align-items: center;
  gap: 6px;
  margin-top: 8px;
  padding: 8px 12px;
  background: #f0f9ff;
  border-radius: 6px;
  font-size: 12px;
  color: #409eff;
  
  .el-icon {
    font-size: 14px;
  }
}

.role-option {
  display: flex;
  align-items: center;
  gap: 8px;
  width: 100%;
}

.role-name {
  font-weight: 500;
  color: #1f2d3d;
}

.role-description {
  flex: 1;
  font-size: 12px;
  color: #6b7280;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.role-system-tag {
  margin-left: auto;
}

.permissions-section {
  width: 100%;
}

.permissions-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12px;
}

.permissions-title {
  font-weight: 500;
  color: #374151;
  font-size: 14px;
}

.select-all-btn,
.clear-all-btn {
  padding: 4px 8px;
  font-size: 12px;
}

.permissions-group {
  display: flex;
  flex-direction: column;
  gap: 12px;
  padding: 16px;
  background: #fafbfc;
  border-radius: 8px;
  border: 1px solid #e5e7eb;
}

.permission-modules {
  width: 100%;
  
  :deep(.el-collapse-item) {
    margin-bottom: 8px;
    border: 1px solid #e5e7eb;
    border-radius: 6px;
    background: #ffffff;
    
    &:last-child {
      margin-bottom: 0;
    }
  }
  
  :deep(.el-collapse-item__header) {
    padding: 12px 16px;
    background: #f9fafb;
    border-bottom: 1px solid #e5e7eb;
    font-weight: 500;
    color: #374151;
    
    &:hover {
      background: #f3f4f6;
    }
  }
  
  :deep(.el-collapse-item__content) {
    padding: 0;
  }
}

.permission-module-item {
  .module-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;
    gap: 8px;
  }
  
  .module-title {
    font-weight: 500;
    color: #374151;
    font-size: 14px;
  }
  
  .module-select-btn,
  .module-clear-btn {
    padding: 2px 6px;
    font-size: 12px;
    margin-left: auto;
  }
}

.module-permissions {
  display: flex;
  flex-direction: column;
  gap: 8px;
  padding: 12px 16px;
  background: #ffffff;
}

.permission-item {
  display: flex;
  align-items: center;
}

.permission-checkbox {
  width: 100%;
  margin: 0;
  
  :deep(.el-checkbox__label) {
    width: 100%;
    padding-left: 8px;
  }
}

.permission-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
}

.permission-label {
  font-weight: 500;
  color: #1f2d3d;
  font-size: 14px;
}

.permission-code {
  font-size: 12px;
  color: #9ca3af;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  background: #f3f4f6;
  padding: 2px 6px;
  border-radius: 4px;
}

.permissions-empty {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px;
  background: #fef3c7;
  border-radius: 6px;
  color: #92400e;
  font-size: 13px;
  
  .el-icon {
    font-size: 16px;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  
  .el-button {
    min-width: 100px;
  }
}

.member-summary {
  display: flex;
  align-items: center;
  gap: 12px;
}

.summary-meta {
  display: flex;
  flex-direction: column;
}

.summary-name {
  font-weight: 600;
}

.summary-email {
  font-size: 13px;
  color: #8b9bb4;
}

@media (max-width: 991px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }

  .header-actions {
    width: 100%;
    justify-content: flex-start;
  }

  .filter-form {
    flex-direction: column;
    align-items: flex-start;
  }
}
</style>

